package com.sales.service.data.transaction;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.sales.service.constants.ServiceConstants;
import com.sales.service.data.transaction.containers.ContactContainer;
import com.sales.service.data.transaction.notifier.ResponseListeners;
import com.sales.service.data.transaction.notifier.UINotifier;
import com.sales.service.http.ServiceRequest;
import com.sales.service.queue.ServiceQueueManager;
import com.sales.service.utils.Utility;

/**
 * This class is used to create the request url for the contact information.
 * the request is made and sent to the queue.
 * with the notifier concept to throw the output of the request from the thread
 * to the UI.
 * 
 * @author Sega
 *
 */
public class ContactTransaction extends AbstractTransaction implements ResponseListeners{

	/**
	 * Strings for debugging process by log.i method
	 */
	private static final String TagProject = "SalesService";
	private static final String TagPage = "ContactTransc ::";
	
	/**
	 * Declaration of the notifier.
	 */
	private final UINotifier notify;

	/**
	 * constructor - is used to initiate the request for the thread
	 * this is done by the abstract method.
	 * 
	 * @param notify - the class to notify is obtained
	 */
	public ContactTransaction(UINotifier notify){
		this.notify = notify;
		initiateTransaction();
	}

	/* (non-Javadoc)
	 * @see com.sales.service.data.transaction.AbstractTransaction#initiateTransaction()
	 * 
	 * this is the abstract method overridden to initiate the thread request and 
	 * to queue.
	 *
	 */
	@Override
	protected void initiateTransaction() {
		String contactUrl = getBaseUrl() + ServiceConstants.SF_Q_GET_CONTACT;
		ServiceRequest contactRequest = new ServiceRequest();
		contactRequest.setRequesturl(contactUrl);
		contactRequest.setResponseListener(this);
		ServiceQueueManager.getInstance().queuePut(contactRequest);
		Log.i(TagProject, TagPage + "contactUrl: " + contactRequest.getRequesturl());
	}
	
	/* (non-Javadoc)
	 * @see com.sales.service.data.transaction.notifier.ResponseListeners#executeResponse(java.io.InputStream)
	 * 
	 * This is the overridden method of RsponseListener class
	 * to get the content of the entity.
	 *
	 */
	@Override
	public void executeResponse(InputStream response) throws JSONException,	IOException {
		Log.i(TagProject, TagPage + " ContactResponse obtained.");
		String res = Utility.WiteFiletosd(response, "Contact.json");
		Log.i(TagProject, TagPage + " res: " + res);
//		deserializeJson(res);
	}

	/* (non-Javadoc)
	 * @see com.sales.service.data.transaction.AbstractTransaction#deserializeJson(java.lang.String)
	 * 
	 * This method is used to store the datas available in the obtained entity
	 * in a array list of the respective container object.
	 * then it handles them as the message and updates the UI as onsuccess method.
	 * 
	 */
	@Override
	protected void deserializeJson(String response) throws JSONException {
		
		JSONObject jsonObject = new JSONObject(response);
		JSONArray recordresonse = jsonObject.getJSONArray("records");
		
		String totalsize = jsonObject.getString("totalSize");
		// String done =jsonObject.getString("done");
		Log.i(TagProject, TagPage + "Total Size: " + totalsize);
		
		ArrayList<Object> arrayContactResult = new ArrayList<Object>();
		ContactContainer container[] = new ContactContainer[recordresonse.length()];
		for(int index = 0; index<recordresonse.length(); index++){
			
			JSONObject recordobject = recordresonse.getJSONObject(index);

			container[index] = new ContactContainer();
			container[index].setCompanyName(recordobject.getString("Name"));

			arrayContactResult.add(container[index]);
			
		}
		
		Message msg = new Message();
		msg.obj = arrayContactResult;
		handler.sendMessage(msg);
	}

	/**
	 * This is the handler used to send the result of the thread to the 
	 * UI as a message.
	 */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			ArrayList<Object> arrayContactResult=(ArrayList<Object>) msg.obj; 
			
			if (arrayContactResult.size() != 0) {
				Log.i(TagProject, TagPage + "All records Obtained and Notified.");
				notify.onSuccess(arrayContactResult);
			} else {
				Log.i(TagProject, TagPage + "NO records.");
				notify.onError();
			}
		}
	};
	
}